define(['app'], function(app) {
    app.controller('SharedBlogsController', function($scope, $compile, $http, xDialog, toastr) {
        var self = this;
        self.query = '';
        self.page = { current: 1, total: 0, size: 10 };

        self.selected = '0';
        self.categories = [];
        self.articles = [];
        var articles = articlesBackup = [];

        self.init = function() {
            loadBlogs();
            $scope.$watch('vm.page.current', function() {
                $('.x-blog-article>.x-view-scope').scrollTop(0);
            });
        }

        function loadBlogs() {
            $http.get('/blog/blogs.json').then(function(response) {
                // Article
                articles = response.data.articles;
                articlesBackup = angular.copy(articles);

                // Category
                var categories = response.data.categories;
                categories.unshift({
                    id: '0',
                    name: '全部分类',
                    root: true
                });
                // Count article by category
                var counts = _.countBy(articles, function(article) {
                    return article.category;
                });
                _.forEach(categories, function(category, i) {
                    if (i == 0) {
                        category.count = articles.length;
                    } else {
                        category.count = (counts[category.id] ? counts[category.id] : 0);
                    }
                });
                self.categories = categories;

                // Check selected and query
                if (self.selected != '0') {
                    if (!_.find(categories, function(category) {
                        return category.id == self.selected;
                    })) {
                        self.selected = '0';
                    }
                }
                self.changeCategory(self.selected, true);
            });
        }

        self.search = function() {
            self.changeCategory(self.selected, true);
        }

        self.changePage = function(page) {
            if (_.isEmpty(articles)) {
                self.articles = [];
            } else {
                var start = (page - 1) * self.page.size,
                    end = page * self.page.size;
                self.articles = articles.slice(start, end);
            }
        }

        self.changeCategory = function(category, changable) {
            if (changable) {
                var rquery = new RegExp(self.query, 'i');
                articles = _.filter(articlesBackup, function(article) {
                    if (!rquery.test(article.title) && !_.find(article.tags, function(tag) {
                        return rquery.test(tag);
                    })) {
                        return false;
                    }
                    if (category != '0' && article.category != category) {
                        return false;
                    }
                    return true;
                });
                self.page.current = 1;
                self.page.total = articles.length;
                self.changePage(1);
            }
        }

        self.editCategory = function(category) {
            var params = category ?
                    { id: category.id, category: category.name } : { id: null, category: '' };
            params.categories = self.categories;
            xDialog.open().editCategory(params).then(function(result) {
                if (result) {
                    loadBlogs();
                }
            });
        }

        self.removeCategory = function(category) {
            xDialog.confirm('确认信息', '您确定要删除【' + category.name + '】吗？').then(function(yes) {
                if (yes) {
                    $http.delete('/mock/blog/delete?category=' + category.id).then(function(response) {
                        if (response.data == 'locked') {
                            xDialog.alert('提示信息', '已有博客分类在编辑，请稍候再试！');
                        } else if (response.data == 'used') {
                            xDialog.alert('提示信息', '博客分类已被使用，不可以删除！');
                        } else if (response.status == 200) {
                            if (response.data) {
                                if (self.selected == category.id) {
                                    self.selected = '0';
                                }
                                loadBlogs();
                                toastr.success('博客分类【' + category.name + '】已删除！');
                            }
                        }
                    });
                }
            });
        }

        self.removeArticle = function(article) {
            xDialog.confirm('确认信息', '您确定要删除【' + article.title + '】吗？').then(function(yes) {
                if (yes) {
                    $http.delete('/mock/blog/delete?article=' + article.id).then(function(response) {
                        if (response.data == 'locked') {
                            xDialog.alert('提示信息', '已有博客在编辑，请稍候再试！');
                        } else if (response.status == 200) {
                            if (response.data) {
                                loadBlogs();
                                toastr.success('博客【' + article.title + '】已删除！');
                            }
                        }
                    });
                }
            });
        }

        self.callback = function(height, width, refresh) {
            // Toolbar
            if (refresh) {
                $('.navbar-form').append($compile($('#opt-toolbar').html())($scope));
            }
        }
    });
});
